package routes

import (
	"simple-crm/config"
	"simple-crm/controllers"
	"simple-crm/middleware"
	"simple-crm/services"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// SetupAPIRoutes 设置API路由
func SetupAPIRoutes(r *gin.Engine, db *gorm.DB, cfg *config.Config) {
	// 创建服务
	pushService := services.NewPushService(db)
	permissionService := services.NewPermissionService(db)
	userService := services.NewUserService(db, cfg)

	// 创建中间件
	permissionMiddleware := middleware.NewPermissionMiddleware(permissionService)

	// 创建控制器
	authController := controllers.NewAuthController(db, cfg)
	customerController := controllers.NewCustomerController(db)
	partnerController := controllers.NewPartnerController(db)
	pushController := controllers.NewPushController(db, pushService)
	systemController := controllers.NewSystemController(db, permissionService)
	userController := controllers.NewUserController(db, userService, permissionService)
	roleController := controllers.NewRoleController(db, permissionService)
	permissionController := controllers.NewPermissionController(db)
	dictDataController := controllers.NewDictDataController(db)

	// 公开路由（不需要认证）
	public := r.Group("/api/v1")
	{
		// 认证相关
		auth := public.Group("/auth")
		{
			auth.POST("/login", authController.Login)
			auth.POST("/register", authController.Register)
		}
	}

	// 需要认证的路由
	protected := r.Group("/api/v1")

	protected.Use(middleware.AuthMiddleware(db, cfg))
	{
		// 认证相关
		auth := protected.Group("/auth")
		{
			auth.POST("/logout", authController.Logout)
			auth.GET("/check-session", authController.CheckSession)
			auth.GET("/profile", authController.GetProfile)
			auth.GET("/verify-session", authController.VerifySession)
			auth.GET("/index", authController.Index)
			auth.GET("/logout", authController.Logout)          // 退出登录
			auth.POST("/profile", authController.UpdateProfile) // 更新用户资料
			auth.POST("/password", authController.Password)
		}

		// 仪表板统计
		dashboard := protected.Group("/dashboard")
		{
			dashboard.GET("/stats", systemController.GetDashboardStats)
		}

		// 客户管理
		customers := protected.Group("/customers")
		customers.Use(middleware.RequireAnyPermission(db, []string{"customer.view", "customer.create", "customer.update", "customer.delete"}))
		{
			customers.GET("", customerController.GetCustomers)
			customers.GET("/stats", customerController.GetCustomerStats)
			customers.GET("/filters", customerController.GetCustomerFilters)
			customers.GET("/:id", customerController.GetCustomer)
			customers.POST("", permissionMiddleware.RequirePermission("customer.create"), customerController.CreateCustomer)
			customers.PUT("/:id", permissionMiddleware.RequirePermission("customer.update"), customerController.UpdateCustomer)
			customers.DELETE("/:id", permissionMiddleware.RequirePermission("customer.delete"), customerController.DeleteCustomer)
			customers.PATCH("/:id/status", permissionMiddleware.RequirePermission("customer.update"), customerController.UpdateCustomerStatus)

			// 批量操作
			customers.PUT("/batch-status", permissionMiddleware.RequirePermission("customer.update"), customerController.BatchUpdateStatus)
			customers.DELETE("/batch-delete", permissionMiddleware.RequirePermission("customer.delete"), customerController.BatchDelete)

			// 导入导出
			customers.POST("/import", permissionMiddleware.RequirePermission("customer.create"), customerController.ImportCustomers)
			customers.GET("/export", permissionMiddleware.RequirePermission("customer.view"), customerController.ExportCustomers)
		}

		// 合作机构管理
		partners := protected.Group("/partners")
		partners.Use(middleware.RequireAnyPermission(db, []string{"partner.view", "partner.create", "partner.update", "partner.delete"}))
		{
			partners.GET("", partnerController.GetPartners)
			partners.GET("/stats", partnerController.GetPartnerStats)
			partners.GET("/filters", partnerController.GetPartnerFilters)
			partners.GET("/cities", partnerController.GetCities)
			partners.GET("/subjects", partnerController.GetSubjects)
			partners.GET("/active", partnerController.GetActivePartners)
			partners.GET("/by-city", partnerController.GetPartnersByCity)
			partners.GET("/by-subject", partnerController.GetPartnersBySubject)
			partners.GET("/:id", partnerController.GetPartner)
			partners.GET("/:id/stats", partnerController.GetPartnerDetailStats)
			partners.GET("/:id/activities", partnerController.GetPartnerActivities)
			partners.POST("", permissionMiddleware.RequirePermission("partner.create"), partnerController.CreatePartner)
			partners.PUT("/:id", permissionMiddleware.RequirePermission("partner.update"), partnerController.UpdatePartner)
			partners.PUT("/:id/status", permissionMiddleware.RequirePermission("partner.update"), partnerController.UpdatePartnerStatus)
			partners.DELETE("/:id", permissionMiddleware.RequirePermission("partner.delete"), partnerController.DeletePartner)
			partners.PATCH("/:id/status", permissionMiddleware.RequirePermission("partner.update"), partnerController.UpdatePartnerStatus)
		}

		// 推送管理
		push := protected.Group("/push")
		push.Use(middleware.RequireAnyPermission(db, []string{"push.manual", "push.view"}))
		{
			// 推送操作
			push.POST("/manual", permissionMiddleware.RequirePermission("push.manual"), pushController.ManualPush)
			push.POST("/retry/:id", permissionMiddleware.RequirePermission("push.retry"), pushController.RetryPush)

			// 推送记录
			push.GET("/records", permissionMiddleware.RequirePermission("push.view"), pushController.GetPushRecords)
			push.GET("/records/:id", permissionMiddleware.RequirePermission("push.view"), pushController.GetPushRecord)

			// 推荐和统计
			push.GET("/recommended/:customer_id", permissionMiddleware.RequirePermission("push.view"), pushController.GetRecommendedPartners)

			push.GET("/stats", permissionMiddleware.RequirePermission("push.stats"), pushController.GetPushStats)
		}

		// 用户管理
		userGroup := protected.Group("/users")
		userGroup.Use(permissionMiddleware.RequirePermission("system.user.view"))
		{
			userGroup.GET("", userController.GetUsers)
			userGroup.GET("/:id", userController.GetUserByID)
			userGroup.POST("", permissionMiddleware.RequirePermission("system.user.create"), userController.CreateUser)
			userGroup.PUT("/:id", permissionMiddleware.RequirePermission("system.user.update"), userController.UpdateUser)
			userGroup.DELETE("/:id", permissionMiddleware.RequirePermission("system.user.delete"), userController.DeleteUser)
			userGroup.POST("/:id/roles/:role_id", permissionMiddleware.RequirePermission("system.user.update"), userController.AssignRole)
			userGroup.DELETE("/:id/roles/:role_id", permissionMiddleware.RequirePermission("system.user.update"), userController.RemoveRole)
			userGroup.POST("/:id/roles", permissionMiddleware.RequirePermission("system.user.update"), userController.AssignUserRole)
			userGroup.GET("/:id/roles", userController.GetUserRoles)
			userGroup.GET("/stats", userController.GetUserStats)
			userGroup.POST("/batch-delete", permissionMiddleware.RequirePermission("system.user.delete"), userController.BatchDeleteUsers)
			userGroup.POST("/:id/reset-password", permissionMiddleware.RequirePermission("system.user.update"), userController.ResetPassword)
			userGroup.PUT("/:id/status", permissionMiddleware.RequirePermission("system.user.update"), userController.ToggleUserStatus)
			userGroup.GET("/check-username", userController.CheckUserExists)
			userGroup.GET("/check-email", userController.CheckEmailExists)
			userGroup.GET("/:id/login-history", userController.GetUserLoginHistory)
		}

		// 用户个人资料管理
		profileGroup := protected.Group("/profile")
		{
			profileGroup.GET("", userController.GetUserProfile)
			profileGroup.PUT("", userController.UpdateUserProfile)
			profileGroup.PUT("/password", userController.ChangePassword)
			profileGroup.GET("/roles", userController.GetUserRoles)
			profileGroup.GET("/login-history", userController.GetUserLoginHistory)
		}

		// 系统管理
		system := protected.Group("/system")
		system.Use(middleware.RequireAnyPermission(db, []string{"system.role", "permission.view", "system.log"}))
		{

			// 角色管理
			roles := system.Group("/roles")
			{
				roles.GET("", permissionMiddleware.RequirePermission("system.role.view"), roleController.GetRoles)
				roles.GET("/stats", permissionMiddleware.RequirePermission("system.role.view"), roleController.GetRoleStats)
				roles.GET("/check-name", permissionMiddleware.RequirePermission("system.role.view"), roleController.CheckRoleName)
				roles.GET("/:id", permissionMiddleware.RequirePermission("system.role.view"), roleController.GetRole)
				roles.GET("/:id/permissions", permissionMiddleware.RequirePermission("system.role.view"), roleController.GetRolePermissions)
				roles.GET("/:id/users", permissionMiddleware.RequirePermission("system.role.view"), roleController.GetRoleUsers)
				roles.POST("", permissionMiddleware.RequirePermission("system.role.create"), roleController.CreateRole)
				roles.POST("/:id/toggle-status", permissionMiddleware.RequirePermission("system.role.update"), roleController.ToggleRoleStatus)
				roles.POST("/:id/permissions", permissionMiddleware.RequirePermission("system.role.update"), roleController.UpdateRolePermissions)
				roles.POST("/batch-delete", permissionMiddleware.RequirePermission("system.role.delete"), roleController.BatchDeleteRoles)
				roles.PUT("/:id", permissionMiddleware.RequirePermission("system.role.update"), roleController.UpdateRole)
				roles.DELETE("/:id", permissionMiddleware.RequirePermission("system.role.delete"), roleController.DeleteRole)
			}

			// 权限管理
			permissions := system.Group("/permissions")
			permissions.Use(permissionMiddleware.RequirePermission("permission.view"))
			{
				permissions.GET("", permissionController.GetPermissions)
				permissions.GET("/stats", permissionController.GetPermissionStats)
				permissions.GET("/resources", permissionController.GetPermissionResources)
				permissions.GET("/tree", permissionController.GetPermissionTree)
				permissions.GET("/:id", permissionController.GetPermission)
				permissions.POST("", permissionMiddleware.RequirePermission("permission.create"), permissionController.CreatePermission)
				permissions.POST("/batch-delete", permissionMiddleware.RequirePermission("permission.delete"), permissionController.BatchDeletePermissions)
				permissions.PUT("/:id", permissionMiddleware.RequirePermission("permission.update"), permissionController.UpdatePermission)
				permissions.DELETE("/:id", permissionMiddleware.RequirePermission("permission.delete"), permissionController.DeletePermission)
			}

			// 操作日志
			logs := system.Group("/logs")
			logs.Use(permissionMiddleware.RequirePermission("system.log.view"))
			{
				logs.GET("", systemController.GetOperationLogs)
			}

			// 字典数据管理
			dictData := system.Group("/dictData")
			{
				dictData.GET("/treeData", dictDataController.GetTreeData)
			}

			// 系统统计
			system.GET("/stats", systemController.GetSystemStats)
		}
	}

	// 健康检查
	r.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"status":  "ok",
			"message": "Simple CRM API is running",
		})
	})
}
